<template>
  <div class="viewContain">
    <el-form>
      <el-row>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 6 }">
          <el-form-item label="退款状态 :">
            <el-select v-model="listQuery.status" placeholder="请选择" clearable>
              <el-option
                v-for="item in refundStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 10 }" :xl="{ span: 10 }">
          <el-form-item label="起止时间 :">
            <el-date-picker
              v-model="listQuery.time"
              size="small"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              unlink-panels
              @change="dateChange"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 6 }">
          <el-form-item>
            <el-button size="mini" type="primary" @click="handleSearch">查询</el-button>
            <el-button size="mini" type="primary" plain @click="handleReload">重置</el-button>
            <el-button size="mini" type="primary" @click="handleAdd">新增</el-button>
            <el-button size="mini" type="primary" @click="handleBack">返回</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <div style="text-align:right">
        <el-button size="mini" type="primary" @click="handleSearch">查询</el-button>
        <el-button size="mini" type="primary" plain @click="handleReload">重置</el-button>
        <el-button size="mini" type="primary" @click="handleAdd">新增</el-button>
        <el-button size="mini" type="primary" @click="handleBack">返回</el-button>
      </div> -->
    </el-form>
    <!-- 退款对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      width="1000px"
      @close="closeDialog"
    >
      <div class="refundInfo">
        <div>当前站点 : {{ currentOrgName }}</div>
        <div><el-button size="mini" type="primary" @click="handleAddRefundItem">新增</el-button></div>
      </div>
      <el-form ref="formData" :model="formData" size="small" :rules="rules" label-width="100px">
        <div class="refundTable">
          <el-table
            ref="table"
            v-loading="loading"
            fit
            stripe
            :data="tableDataRefund"
            border
            size="mini"
            style="margin-bottom:20px"
          >
            <el-table-column align="center" label="序号" type="index" width="50">
              <template slot-scope="scope">
                <span>{{ (listQuery.pageNo - 1) * listQuery.pageSize + scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="code" align="center" label="商品信息">
              <template slot-scope="scope">
                <el-select v-model="scope.row.code" placeholder="请选择" focus filterable clearable style="width:100%">
                  <el-option
                    v-for="item in goodList"
                    :key="item.value"
                    :label="item.label + '(' + item.code + ')'"
                    :value="item.code"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="stock" align="center" label="商品数量" width="100">
              <template slot-scope="scope">
                <el-input v-model="scope.row.stock" />
              </template>
            </el-table-column>
            <el-table-column align="center" fixed="right" label="操作" width="50">
              <template slot-scope="scope">
                <el-button class="text-button el-button--danger" size="mini" @click="handleDeleteRefundItem(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="物流退货" name="first">
            <el-form-item label="物流公司 :" prop="logisticsCompany">
              <el-select v-model="formData.logisticsCompany" filterable placeholder="请选择" clearable style="width:100%">
                <el-option
                  v-for="item in logisticsList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="物流单号 :" prop="trackNum">
              <el-input v-model="formData.trackNum" clearable style="width:100%" />
            </el-form-item>
            <el-form-item label="发货人 :" prop="shipper">
              <el-input v-model="formData.shipper" style="width:100%" clearable />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="其它" name="second">
            <el-form-item label="备注 :" prop="remark">
              <el-input v-model="formData.remark" clearable type="textarea" :rows="2" />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
        <el-form-item>
          <div style="text-align:right">
            <el-button size="mini" type="primary" plain @click="handleClose">取消</el-button>
            <el-button size="mini" type="primary" @click="handleSubmit">提交</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-table
      ref="table"
      v-loading="loading"
      fit
      stripe
      :data="tableData"
      border
      size="mini"
    >
      <el-table-column align="center" label="序号" type="index" width="50">
        <template slot-scope="scope">
          <span>{{ (listQuery.pageNo - 1) * listQuery.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="returnNum" align="center" label="退货单号" />
      <el-table-column prop="createTime" align="center" label="退货时间" />
      <el-table-column prop="totalPrice" align="center" label="商品总额(元)" />
      <el-table-column prop="status" align="center" label="退款状态" />
      <el-table-column align="center" fixed="right" label="操作" width="250">
        <template slot-scope="scope">
          <!-- type: 1 自提   type: 物流 -->
          <el-button class="text-button" size="mini" @click="handleDetail(scope.row.returnNum,scope.row.totalPrice)">详细</el-button>
          <el-button :disabled="scope.row.type === '1'" class="text-button" size="mini" @click="handleLogistics(scope.row)">物流</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total-count="totalCount"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { commonMixin } from '@v/mixin/commonMixin.js'
import ComApiUrl from '@a/comomApi.js'
import { queryProductList } from '@a/business/site.js'
import { mapGetters } from 'vuex'
import pagination from '@/components/pagination/index.vue'
export default {
  components: { pagination },
  mixins: [commonMixin],
  data() {
    return {
      comApiUrlList: new ComApiUrl('/member/api/returnGoods/queryReturnRecord'),
      comApiUrlAdd: new ComApiUrl('/member/api/returnGoods/addReturnRecord'),
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        startTime: '',
        endTime: '',
        orgId: ''
      },
      formData: {
        returnGoodsBeans: [], // 商品集合
        logisticsCompany: '', // 物流公司
        trackNum: '', // 物流单号
        shipper: '', // 发货人
        type: '0', // 退货方式（默认物流）
        orgId: '', //  机构id
        remark: '',
        returnNum: ''
      },
      formDataOhther: {
        remark: ''
      },
      currentOrgName: '', // 当前站点名称
      refundStatus: [{ label: '未退款', value: '0' }, { label: '已退款', value: '1' }],
      tableDataRefund: [{}],
      dialogTitle: '退货单',
      dialogFormVisible: false,
      goodList: [],
      input: '',
      activeName: 'first',
      value: '',
      rules: {
        trackNum: [
          { required: true, message: '物流单号不能为空!', trigger: 'blur' }
        ],
        shipper: [
          { required: true, message: '发货人不能为空!', trigger: 'blur' }
        ],
        logisticsCompany: [
          { required: true, message: '物流公司不能为空!', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '备注不能为空!', trigger: 'blur' }
        ]
      },
      rule: true,
      orgId: ''
    }
  },
  computed: {
    ...mapGetters(['logisticsList'])
  },
  mounted() {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    const { isAdminRole, orgId, orgName } = userInfo
    const id = this.$route.params.id
    this.orgId = id
    isAdminRole === '1' ? this.listQuery.orgId = id : this.listQuery.orgId = orgId
    isAdminRole === '1' ? this.formData.orgId = id : this.formData.orgId = orgId
    isAdminRole === '1' ? this.currentOrgName = localStorage.getItem('orgName') : this.currentOrgName = orgName
    this.getList()
  },
  methods: {
    // 新增
    handleAdd() {
      this.dialogFormVisible = true
      // 商品列表下拉框
      this.tableDataRefund = [{}]
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      const { userId, isAdminRole } = userInfo
      const id = this.$route.params.id
      let orgId = ''
      isAdminRole === '1' ? orgId = id : orgId = userInfo.orgId
      queryProductList({ id: userId, orgId }).then(res => {
        if (res.code === 0) {
          this.goodList = res.data
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    // 新增退款条例
    handleAddRefundItem() {
      this.tableDataRefund.push({})
    },
    dateChange(time) {
      console.log(time)
      this.listQuery.startTime = time[0]
      this.listQuery.endTime = time[1]
    },
    // 提交退货单
    handleSubmit() {
      // console.log('=====退款表格', this.tableDataRefund)
      this.formData.returnGoodsBeans = this.tableDataRefund
      console.log(this.formData.returnGoodsBeans)
      for (var i = 0; i < this.formData.returnGoodsBeans.length; i++) {
        if (!this.formData.returnGoodsBeans[i].stock) {
          this.$message({
            type: 'warning',
            message: '商品采购数量不能为空!'
          })
          this.rule = false
          break
        } else {
          const reg = new RegExp(/^[0-9]*[1-9][0-9]*$/) // 商品数量要是大于0的正整数
          const flag = reg.test(this.formData.returnGoodsBeans[i].stock)
          if (!flag) {
            this.$message({
              type: 'warning',
              message: '商品数量为大于0的正整数!'
            })
            this.rule = false
            break
          } else {
            this.rule = true
          }
        }
        if (!this.formData.returnGoodsBeans[i].code) {
          this.$message({
            type: 'warning',
            message: '请选择商品!'
          })
          this.rule = false
          break
        } else {
          this.rule = true
        }
      }
      // 判断重复的商品
      const code = this.formData.returnGoodsBeans.map(item => item.code)
      console.log(code)
      const codeSet = new Set(code)
      if (codeSet.size === code.length) {
        console.log('不存在同个值')
      } else {
        this.$message({
          type: 'warning',
          message: '该商品已经在退货单中!'
        })
        this.rule = false
      }
      if (this.formData.type === '0') {
        delete this.rules.remark
        this.$refs.formData.validate(valide => {
          // console.log('=====退款入参表单', this.formData)
          console.log('=====this.rule', this.rule)
          if (valide && this.rule) {
            console.log('====rule为true，执行提交操作')
            this.create()
          }
        })
      } else {
        delete this.rules.trackNum
        delete this.rules.shipper
        delete this.rules.logisticsCompany
        this.$refs.formData.validate(valide => {
          if (valide && this.rule) {
            this.create()
          }
        })
      }
    },
    // 删除退款条例
    handleDeleteRefundItem(index) {
      console.log(index)
      this.tableDataRefund.splice(index, 1)
    },
    // 取消退款
    handleClose() {
      this.dialogFormVisible = false
      this.$refs.formData.resetFields()
    },
    handleClick(tab) {
      // console.log(tab)
      this.formData.type = tab.index
    },
    // 详细
    handleDetail(returnNum, totalPrice) {
      this.$router.push('/business/address/refund/detail/' + returnNum)
      localStorage.setItem('orgId', this.orgId)
      localStorage.setItem('totalPrice', totalPrice)
    },
    // 物流
    handleLogistics(row) {
      const { logisticsCompany, trackNum } = row
      if (logisticsCompany === 'zt') {
        window.open('https://www.zto.com/express/expressCheck.html')
      } else if (logisticsCompany === 'htky') {
        window.open('http://800bestex.com/bill/track')
      } else {
        window.open('http://www.kuaidi100.com/all/' + logisticsCompany + '.shtml?mscomnu=' + trackNum)
      }
    },
    // 重置
    handleReload() {
      this.listQuery = {
        pageNo: 1,
        pageSize: 10
      }
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      const { isAdminRole, orgId } = userInfo
      const id = this.$route.params.id
      isAdminRole === '1' ? this.listQuery.orgId = id : this.listQuery.orgId = orgId
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.refundInfo {
  width: 100%;
  height: 50px;
  line-height: 50px;
  display: flex;
  justify-content:space-between;
}
.refundTable {
  width: 100%;
  height: 250px;
  overflow: auto;
}
</style>
